#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
诊断信息同步问题
"""

import os
import subprocess
import socket
import time
import sqlite3
import json

def check_port(port):
    """检查端口是否被占用"""
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex(('localhost', port))
        sock.close()
        return result == 0
    except:
        return False

def check_processes():
    """检查相关进程"""
    print("🔍 检查相关进程...")
    try:
        # 检查Python进程
        result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq python.exe'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            lines = result.stdout.split('\n')
            python_processes = [line for line in lines if 'python.exe' in line]
            print(f"🐍 Python进程数量: {len(python_processes)}")
            for process in python_processes:
                if process.strip():
                    print(f"   {process.strip()}")
        
        # 检查端口占用
        result = subprocess.run(['netstat', '-an'], capture_output=True, text=True)
        if result.returncode == 0:
            lines = result.stdout.split('\n')
            port_8080 = [line for line in lines if ':8080' in line]
            print(f"\n🔌 端口8080连接:")
            for conn in port_8080:
                if conn.strip():
                    print(f"   {conn.strip()}")
    except Exception as e:
        print(f"❌ 进程检查失败: {e}")

def check_server_files():
    """检查服务器相关文件"""
    print("\n📁 检查服务器文件...")
    
    files_to_check = [
        'complete_permission_server.py',
        'complete_patient_management.db',
        'websocket_server.py',
        'patient_management.db'
    ]
    
    for file in files_to_check:
        if os.path.exists(file):
            print(f"✅ {file} - 存在")
            if file.endswith('.db'):
                check_database(file)
        else:
            print(f"❌ {file} - 不存在")

def check_database(db_file):
    """检查数据库内容"""
    try:
        conn = sqlite3.connect(db_file)
        cursor = conn.cursor()
        
        # 检查表结构
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        tables = cursor.fetchall()
        print(f"   📊 {db_file} 包含表: {[t[0] for t in tables]}")
        
        # 检查用户数据
        if any('users' in str(t) for t in tables):
            cursor.execute("SELECT COUNT(*) FROM users")
            user_count = cursor.fetchone()[0]
            print(f"   👥 用户数量: {user_count}")
        
        # 检查患者数据
        if any('patients' in str(t) for t in tables):
            cursor.execute("SELECT COUNT(*) FROM patients")
            patient_count = cursor.fetchone()[0]
            print(f"   🏥 患者数量: {patient_count}")
        
        conn.close()
    except Exception as e:
        print(f"   ❌ 数据库检查失败: {e}")

def check_android_config():
    """检查Android配置"""
    print("\n📱 检查Android配置...")
    
    websocket_file = "app/src/main/java/com/example/myapplication/realtime/WebSocketManager.kt"
    
    if os.path.exists(websocket_file):
        print("✅ WebSocketManager.kt 存在")
        
        try:
            with open(websocket_file, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # 检查服务器URL配置
            if 'PUBLIC_SERVER_URL' in content:
                import re
                url_match = re.search(r'PUBLIC_SERVER_URL = "(.*?)"', content)
                if url_match:
                    url = url_match.group(1)
                    print(f"🌐 配置的服务器地址: {url}")
                else:
                    print("⚠️ 找到PUBLIC_SERVER_URL但无法解析")
            else:
                print("❌ 未找到PUBLIC_SERVER_URL配置")
            
            # 检查连接逻辑
            if 'connectToServer' in content:
                print("✅ 包含连接逻辑")
            else:
                print("❌ 缺少连接逻辑")
            
        except Exception as e:
            print(f"❌ 读取WebSocketManager.kt失败: {e}")
    else:
        print("❌ WebSocketManager.kt 不存在")

def start_server_if_needed():
    """如果需要，启动服务器"""
    print("\n🚀 检查服务器状态...")
    
    if check_port(8080):
        print("✅ 端口8080已被占用 (服务器可能在运行)")
        return True
    else:
        print("❌ 端口8080未被占用 (服务器未运行)")
        
        if os.path.exists('complete_permission_server.py'):
            start = input("\n是否启动权限管理服务器? (y/N): ").strip().lower()
            if start in ['y', 'yes']:
                print("🚀 启动服务器...")
                subprocess.Popen(['python', 'complete_permission_server.py'])
                time.sleep(3)
                
                if check_port(8080):
                    print("✅ 服务器启动成功")
                    return True
                else:
                    print("❌ 服务器启动失败")
                    return False
        else:
            print("❌ 找不到complete_permission_server.py")
            return False

def test_websocket_connection():
    """测试WebSocket连接"""
    print("\n🧪 测试WebSocket连接...")
    
    try:
        import asyncio
        import websockets
        
        async def test_connection():
            try:
                async with websockets.connect('ws://localhost:8080', timeout=5) as websocket:
                    # 等待连接确认
                    response = await websocket.recv()
                    data = json.loads(response)
                    
                    if data.get('type') == 'CONNECTION_ACK':
                        print("✅ WebSocket连接成功")
                        print(f"📊 服务器信息: {data.get('data', {})}")
                        return True
                    else:
                        print(f"⚠️ 连接响应异常: {data}")
                        return False
            except Exception as e:
                print(f"❌ WebSocket连接失败: {e}")
                return False
        
        return asyncio.run(test_connection())
        
    except ImportError:
        print("⚠️ 跳过WebSocket测试 (需要安装websockets: pip install websockets)")
        return None

def get_network_info():
    """获取网络信息"""
    print("\n🌐 网络信息...")
    
    try:
        # 获取本机IP地址
        result = subprocess.run(['ipconfig'], capture_output=True, text=True)
        if result.returncode == 0:
            lines = result.stdout.split('\n')
            for i, line in enumerate(lines):
                if 'IPv4' in line and '192.168.' in line or '172.' in line or '10.' in line:
                    ip = line.split(':')[-1].strip()
                    print(f"📍 本机IP地址: {ip}")
                    break
    except Exception as e:
        print(f"❌ 获取网络信息失败: {e}")

def main():
    """主函数"""
    print("🔍 信息同步问题诊断")
    print("=" * 50)
    
    # 检查进程
    check_processes()
    
    # 检查文件
    check_server_files()
    
    # 检查Android配置
    check_android_config()
    
    # 获取网络信息
    get_network_info()
    
    # 启动服务器（如果需要）
    server_running = start_server_if_needed()
    
    if server_running:
        # 测试连接
        test_websocket_connection()
    
    print("\n" + "=" * 50)
    print("🎯 诊断完成！")
    
    print("\n💡 常见同步问题解决方案:")
    print("1. 确保两个设备连接到同一网络")
    print("2. 确保权限管理服务器正在运行")
    print("3. 确保Android应用使用正确的服务器地址")
    print("4. 确保用户已正确登录并有相应权限")
    print("5. 检查防火墙是否阻止了连接")
    
    print("\n📝 下一步建议:")
    if not server_running:
        print("• 启动权限管理服务器: python complete_permission_server.py")
    print("• 重新编译APK: gradlew assembleRelease")
    print("• 重新安装APK到设备")
    print("• 使用测试账号登录验证")

if __name__ == "__main__":
    main() 